﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.HVAC.AuxiliaryCurve
{
	public class DetailArcDraw : AuxiliaryDraw
	{
		public DetailArcDraw(ExternalCommandData amdArgu, Dictionary<XYZ, XYZ> dicXArgu, Dictionary<XYZ, XYZ> dicYArgu, ref ICollection<ElementId> idsArgu) : base(amdArgu, dicXArgu, dicYArgu, ref idsArgu)
		{
		}

		public override bool DrawCurve()
		{
			if (!base.IsInTolerance())
			{
				return false;
			}
			if (this.dicX.Count < 1 && this.dicY.Count < 1)
			{
				return false;
			}
			foreach (KeyValuePair<XYZ, XYZ> keyValuePair in this.dicY)
			{
				DetailCurve detailCurve = this.DrawCircleLine(keyValuePair.Value, keyValuePair.Key, this.GetArcRadius(keyValuePair.Key, keyValuePair.Value));
				this.ids.Add(detailCurve.Id);
			}
			foreach (KeyValuePair<XYZ, XYZ> keyValuePair2 in this.dicX)
			{
				DetailLine detailLine = YJKRevitTools.DrawDetailLine(this.m_CmdData.Application.ActiveUIDocument.Document, keyValuePair2.Key, keyValuePair2.Value);
				this.ids.Add(detailLine.Id);
			}
			YJKRevitTools.SetDetailLineView(this.ids, this.m_CmdData);
			return true;
		}

		private double GetArcRadius(XYZ pnt1, XYZ pnt2)
		{
			return pnt1.DistanceTo(pnt2) * 2.0;
		}

		private XYZ GetCenterCircle(XYZ sPnt, XYZ ePnt, double radius, int radDir = 0)
		{
			XYZ xyz = new XYZ(sPnt.X, sPnt.Y, 0.0);
			XYZ xyz2 = new XYZ(ePnt.X, ePnt.Y, 0.0);
			XYZ xyz3 = xyz.Subtract(xyz2).Normalize();
			XYZ xyz4 = new XYZ(0.0, 0.0, 1.0);
			double num = sPnt.DistanceTo(ePnt) / 2.0;
			double num2 = Math.Sqrt(radius * radius - num * num);
			XYZ xyz5 = xyz3.CrossProduct(xyz4);
			XYZ xyz6 = sPnt.Add(ePnt) / 2.0;
			xyz6 = new XYZ(xyz6.X, xyz6.Y, sPnt.Z);
			XYZ result;
			if (radDir == 0)
			{
				result = xyz6.Subtract(num2 * xyz5).Add(radius * xyz5);
			}
			else
			{
				result = xyz6.Add(num2 * xyz5).Subtract(radius * xyz5);
			}
			return result;
		}

		private DetailCurve DrawCircleLine(XYZ sPnt, XYZ ePnt, double radius)
		{
			Document document = this.m_CmdData.Application.ActiveUIDocument.Document;
			XYZ centerCircle = this.GetCenterCircle(sPnt, ePnt, radius, 0);
			Curve curve = document.CreatYJKArc(sPnt, ePnt, centerCircle);
			return document.Create.NewDetailCurve(document.ActiveView, curve);
		}
	}
}
